<template>
  <div id="manageQuestionView">
    <a-form :model="searchParams" layout="inline">
      <a-form-item field="id" label="题目id" style="min-width: 240px">
        <a-input-number v-model="searchParams.id" placeholder="请输入题目id" />
      </a-form-item>
      <a-form-item field="title" label="名称" style="min-width: 240px">
        <a-input v-model="searchParams.title" placeholder="请输入名称" />
      </a-form-item>
      <a-form-item
        field="userId"
        label="创建题目用户id"
        style="min-width: 240px"
      >
        <a-input-number
          v-model="searchParams.userId"
          placeholder="创建题目用户id"
        />
      </a-form-item>
      <a-form-item field="tags" label="标签" style="min-width: 240px">
        <a-input-tag v-model="searchParams.tags" placeholder="请输入标签" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="doSubmit">查找</a-button>
      </a-form-item>
      <a-button @click="router.push({ path: '/add/question' })" type="primary"
        >创建题目
      </a-button>
    </a-form>
    <a-table
      :ref="tableRef"
      :columns="columns"
      :data="dataList"
      :pagination="pagination"
      @sorter-change="handleSorterChange"
      @page-change="onPageChange"
    >
      <template #tags="{ record }">
        <a-space wrap>
          <a-tag
            v-for="(tag, index) of JSON.parse(record.tags)"
            :key="index"
            color="arcoblue"
            >{{ tag }}
          </a-tag>
        </a-space>
      </template>
      <template #optional="{ record }">
        <a-space>
          <a-button type="primary" @click="doUpdate(record)">修改</a-button>
          <a-button status="danger" @click="doDelete(record)">删除</a-button>
        </a-space>
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watchEffect } from "vue";
import {
  Question,
  QuestionControllerService,
  type QuestionQueryRequest,
} from "../../../api";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import { TableColumnData } from "@arco-design/web-vue";

const tableRef = ref();

const dataList = ref<Array<Question>>([]);
const total = ref<number>(0);
const searchParams = ref<QuestionQueryRequest>({
  id: undefined,
  title: undefined,
  tags: undefined,
  userId: undefined,
  pageSize: 10,
  current: 1,
});
const pagination = reactive({
  ...searchParams.value,
  showTotal: true,
  total: total,
  showJumper: true,
});
const onPageChange = (current: number) => {
  pagination.current = current;
  searchParams.value.current = current;
  loadData();
};
const loadData = async () => {
  const res = await QuestionControllerService.pageQueryQuestion(
    searchParams.value
  );
  if (res.code === 0) {
    dataList.value = res.data?.records ?? [];
    total.value = res.data?.total ?? 0;
  } else {
    message.error("加载失败，" + res.message);
  }
};

/**
 * 监听 searchParams 变量，改变时触发页面的重新加载
 */
watchEffect(() => {
  loadData();
});

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
});

const columns = ref<TableColumnData[]>([
  {
    title: "id",
    dataIndex: "id",
    width: 100,
    sortable: {
      sortDirections: ["ascend", "descend"],
      // 关键：禁用前端排序，触发服务端请求
      sorter: () => true as unknown as number,
    },
  },
  {
    title: "标题",
    dataIndex: "title",
    ellipsis: true,
    tooltip: true,
    width: 200,
  },
  {
    title: "标签",
    dataIndex: "tags",
    slotName: "tags",
    width: 200,
  },
  {
    title: "分值",
    dataIndex: "score",
    width: 100,
  },
  {
    title: "提交数",
    dataIndex: "submit",
    width: 100,
  },
  {
    title: "通过数",
    dataIndex: "accepted",
    width: 100,
  },
  {
    title: "通过率",
    dataIndex: "ratio",
    render: ({ record }) => `${record.ratio ?? "--"}%`,
    width: 100,
    sortable: {
      sortDirections: ["ascend", "descend"],
      // 关键：禁用前端排序，触发服务端请求
      sorter: () => true as unknown as number,
    },
  },
  {
    title: "时间限制",
    dataIndex: "timeLimit",
    // 关键修改点：自定义渲染时间消耗列
    render: ({ record }) => `${record.timeLimit ?? "--"} ms`,
    width: 100,
  },
  {
    title: "内存限制",
    dataIndex: "memoryLimit",
    // 关键修改点：自定义渲染内存消耗列
    render: ({ record }) => `${record.memoryLimit ?? "--"} KB`,
    width: 100,
  },
  {
    title: "创建用户id",
    dataIndex: "userId",
    width: 100,
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    width: 170,
    sortable: {
      sortDirections: ["ascend", "descend"],
      // 关键：禁用前端排序，触发服务端请求
      sorter: () => true as unknown as number,
    },
  },
  {
    title: "修改时间",
    dataIndex: "updateTime",
    width: 170,
    sortable: {
      sortDirections: ["ascend", "descend"],
      // 关键：禁用前端排序，触发服务端请求
      sorter: () => true as unknown as number,
    },
  },
  {
    title: "操作",
    slotName: "optional",
    width: 170,
  },
]);

const doDelete = async (question: Question) => {
  message.loading("正在删除中~");
  const res = await QuestionControllerService.deleteQuestion({
    id: Number(question.id),
  });
  if (res.code === 0) {
    message.success("删除成功");
    await loadData();
  } else {
    message.error(res.message ?? "删除失败");
  }
};

const router = useRouter();

const doUpdate = (question: Question) => {
  router.push({
    path: "/update/question",
    query: {
      id: question.id,
    },
  });
};

// 处理排序逻辑
const handleSorterChange = (
  dataIndex: string,
  direction: string // 明确声明字面量类型
) => {
  searchParams.value.sortField = dataIndex as
    | "id"
    | "ratio"
    | "createTime"
    | "updateTime";
  searchParams.value.sortOrder =
    direction === "ascend"
      ? "ascend"
      : direction === "descend"
      ? "descend"
      : undefined;

  loadData(); // 触发后端请求
};

/**
 * 确认搜索，重新加载数据
 */
const doSubmit = () => {
  // 这里需要重置搜索页号
  searchParams.value = {
    ...searchParams.value,
    current: 1,
  };
};
</script>
